package com.hliushi.netty.protocol;

import com.hliushi.netty.message.LoginRequestMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author llhuang10
 * @date 2021/10/21 19:35
 */
public class MsgCodecTest {

    /**
     * new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0) 解决黏包和半包问题
     */
    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0),
                new LoggingHandler(LogLevel.DEBUG),
                new MessageCodec()
        );

        // readerIndex(16) + length(91) exceeds writerIndex(50): UnpooledSlicedByteBuf(ridx: 16, widx: 50, cap: 50/50, unwrapped: PooledUnsafeDirectByteBuf(ridx: 0, widx: 107, cap: 256))


        // encode
        LoginRequestMessage message = new LoginRequestMessage("zhangsan", "123");
        // channel.writeOutbound(message);

        // decode
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        new MessageCodec().encode(null, message, buf);
        ByteBuf s1 = buf.slice(0, 50);
        ByteBuf s2 = buf.slice(50, buf.readableBytes() - 50);

        // 引用计数2
        s1.retain();
        channel.writeInbound(s1);   // release 1
        channel.writeInbound(s2);
        // channel.writeInbound(buf);

    }
}
